import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ResData } from "@/api/global";

const BASE_URL = import.meta.env.VITE_APP_BASE_API;

const instance = axios.create({
  baseURL: BASE_URL,
  withCredentials: true,
  timeout: 10000,
});

//请求拦截器
instance.interceptors.request.use(
  (config: any) => {
    // 接口权限拦截
    // const store = usePermissioStoreWithOut();
    // const { url = '' } = config;
    // if (!WhiteList.includes(url) && store.getIsAdmin === 0) {
    //   if (!store.getAuths.includes(url)) {
    //     console.log('url', url, store.getIsAdmin);
    //     return Promise.reject('没有操作权限');
    //   }
    // }

    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

//响应拦截器
instance.interceptors.response.use(
  (response: any) => {
    const res = response.data as ResData<any>;

    // 正确状态
    if (res.code === 200) {
      return res.data || true;
    }
    if (res.code === 500) {
      return Promise.reject(res);
    }


    // 异常 TODO
    // showToast(res.msg);
    return undefined;
  },
  (error: any) => {
    console.log("err" + error); // for debug
    
    // 没权限时，不再重复提示
    if (error === "没有操作权限") return;
    // showToast("网络超时，稍后再试吧");
  }
);

const request = <T = any>(
  config: AxiosRequestConfig | string,
  options?: AxiosRequestConfig
): Promise<T> => {
  if (typeof config === "string") {
    if (!options) {
      return instance.request<T, T>({
        url: config,
      });
      // throw new Error('请配置正确的请求参数');
    } else {
      return instance.request<T, T>({
        url: config,
        ...options,
      });
    }
  } else {
    return instance.request<T, T>(config);
  }
};
// get
export function get<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<T> {
  return request({ ...config, method: "GET" }, options);
}
// post
export function post<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<T> {
  return request({ ...config, method: "POST" }, options);
}
// put
export function put<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<T> {
  return request({ ...config, method: "PUT" }, options);
}
// delete
export function delete_<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<T> {
  return request({ ...config, method: "DELETE" }, options);
}

export default request;
export type { AxiosInstance, AxiosResponse };
